"""
    Author:
    Date: 2019-12-19

    Api接口的实现文件
"""

import base64

from entities import cpa_mgr
from utils.log import Log

def api_fetch_access_token(request):
    """ 认证接口 """
    # 提取认证密钥
    authorization = request.META.get('HTTP_AUTHORIZATION', '')
    token = base64.b64decode(authorization[6:]).decode('utf-8')
    Log.info(f"[CPA] fetch access token: authorization={authorization}, b64decode token={token}")
    info = token.split(':')
    if len(info) != 2:
        Log.error(f"[CPA] fetch access token failed for invalid token: token={token}")
        return cpa_mgr.CPA_ERROR_INVALID_TOKEN, None

    # 检验密钥是否合法
    client_id, client_secret = info
    if not cpa_mgr.is_valid_secret(client_id, client_secret):
        return cpa_mgr.CPA_ERROR_INVALID_TOKEN, None

    # 分配access token
    access_token = cpa_mgr.fetch_access_token(client_id)

    # 回应客户端
    data = {
        'access_token': access_token,
    }
    return cpa_mgr.CPA_ERROR_NO_ERROR, data

def api_is_device_exists(request, adid, channel, device_id, os_version, ip, keys):
    """ 检测设备是否存在 """
    # 判断设备是存在
    exists = 1 if cpa_mgr.is_device_exists(device_id) else 0

    # 回应客户端
    data = {
        'exists': exists,
    }
    return cpa_mgr.CPA_ERROR_NO_ERROR, data

def api_is_device_activated(request, adid, channel, device_id, os_version, ip, keys):
    """ 检测设备是否已被激活 """
    # 判断设备是存在
    activated = 1 if cpa_mgr.is_device_exists(device_id) else 0

    # 回应客户端
    data = {
        'activated': activated,
    }
    return cpa_mgr.CPA_ERROR_NO_ERROR, data


if __name__ == '__main__':
    print('ok')
